<template>
  <div class="login">
    <Row
      type="flex"
      justify="center"
      align="middle"
      @keydown.enter.native="handleSubmit"
      style="height:100%"
    >
      <Col class="layout">
        <div>
          <div>
            <Row class="header">
              <img src="../../assets/images/logo.jpg" width="220px">
              <div class="description">iview admin前后端分离开发</div>
            </Row>
          </div>
          <Row>
            <Tabs v-model="tabName">
              <TabPane label="账户密码登录" name="username" icon="md-person">
                <Form
                  ref="usernameLoginForm"
                  :model="form"
                  :rules="rules"
                  class="form"
                  v-if="tabName=='username'"
                >
                  <FormItem prop="username">
                    <Input
                      v-model="form.username"
                      prefix="ios-contact"
                      size="large"
                      clearable
                      placeholder="请输入用户名"
                      autocomplete="off"
                    />
                  </FormItem>
                  <FormItem prop="password">
                    <Input
                      type="password"
                      v-model="form.password"
                      prefix="ios-lock"
                      size="large"
                      password
                      placeholder="请输入密码"
                      autocomplete="off"
                    />
                  </FormItem>
                  <FormItem prop="imgCode">
                    <Row
                      type="flex"
                      justify="space-between"
                      style="align-items: center;overflow: hidden;"
                    >
                      <Input
                        v-model="form.imgCode"
                        size="large"
                        clearable
                        placeholder="请输入图片验证码"
                        :maxlength="10"
                        class="input-verify"
                      />
                      <div class="code-image" style="position:relative;font-size:12px">
<!--                        <Spin v-if="loadingCaptcha" fix></Spin>-->
                        <img
                          :src="captchaImg"
                          @click="getCaptchaImg"
                          alt="加载验证码失败"
                          style="width:110px;cursor:pointer;display:block"
                        />
                      </div>
                    </Row>
                  </FormItem>
                </Form>
              </TabPane>
              <TabPane label="手机短信登录" name="mobile" icon="ios-phone-portrait">
                <Form
                  ref="mobileLoginForm"
                  :model="form"
                  :rules="rules"
                  class="form"
                  v-if="tabName=='mobile'"
                >
                  <FormItem prop="mobile">
                    <Input
                      v-model="form.mobile"
                      prefix="ios-phone-portrait"
                      size="large"
                      clearable
                      placeholder="请输入手机号"
                    />
                  </FormItem>
                  <FormItem prop="smsCode" :error="errorCode">
                    <Row type="flex" justify="space-between">
                      <Input
                        v-model="form.smsCode"
                        prefix="ios-mail-outline"
                        size="large"
                        clearable
                        placeholder="请输入短信验证码"
                        :maxlength="6"
                        class="input-verify"
                      />
                      <Button size="large" :long="false" :ghost="false"  :disabled="clickFlag" @click="sendSmsCode">{{text}}</Button>
                    </Row>
                  </FormItem>
                </Form>
              </TabPane>
            </Tabs>

            <Row type="flex" justify="space-between" align="middle">
              <router-link to="/forgetPass">
                <a class="forget-pass">忘记密码</a>
              </router-link>
            </Row>
            <Row>
              <Button
                class="login-btn"
                type="primary"
                size="large"
                :loading="loading"
                @click="handleSubmit"
                long
              >
                <span v-if="!loading">登录</span>
                <span v-else>登录中</span>
              </Button>
            </Row>
          </Row>
          <Row type="flex" justify="space-between" class="other-login">
            <div class="other-way icons">
              其他方式登录
              <div class="other-icon" @click="toGithubLogin">
                <Icon custom="iconfont icongithub" size="20"></Icon>
              </div>
              <div class="other-icon" @click="toQQLogin">
                <Icon custom="iconfont iconQQ" size="20"></Icon>
              </div>
              <div class="other-icon" @click="toWeixinLogin">
                <Icon custom="iconfont iconweixin" size="20"></Icon>
              </div>
              <div class="other-icon" @click="toPayLogin">
                <Icon custom="iconfont iconumidd17-copy" size="20"></Icon>
              </div>
            </div>
            <router-link to="/register">
              <a class="forget-pass">注册</a>
            </router-link>
          </Row>
        </div>
      </Col>
    </Row>
  </div>
</template>

<script>
import {login,sendCode,smsCodeLogin} from "@/api/login";
import {setToken} from "@/libs/util";
import { timeFix,validatePhone,isNull} from '@/libs/tools'
import {validateMobile} from "@/libs/validate";
import Stomp from 'stompjs'
import SockJS from 'sockjs-client'
export default {
  data(){
    return{
      tabName:'username',
      form:{
        t:null,
      },
      captchaImg:'',
      errorCode:'',
      loading:false,
      clickFlag:false,
      text:'获取验证码',
      socketUrl:'http://127.0.0.1:8080/ws',
      rules:{
        username: [
          {
            required: true,
            message: "账号不能为空",
            trigger: "blur"
          }
        ],
        password: [
          {
            required: true,
            message: "密码不能为空",
            trigger: "blur"
          }
        ],
        imgCode: [
          {
            required: true,
            message: "验证码不能为空",
            trigger: "blur"
          }
        ],
        mobile:[
          {required:true,message:'手机号码不能为空',trigger:'blur'},
          {validator:validateMobile}
        ],
        smsCode: [
          {required:true,message:'短信验证码不能为空',trigger:'blur'}
        ]
      },
      count:60,
    }
  },
  methods: {
    handleSubmit () {
      if(this.tabName=='username'){
        this.$refs.usernameLoginForm.validate(valid => {
          if(valid){
            this.loading = true
            login(this.form.username, this.form.password, this.form.t, this.form.imgCode)
              .then(res => {
                if (res.code == 200) {
                  this.handleSuccess(res)
                } else {
                  this.getCaptchaImg()
                  this.loading = false
                }
              }).catch(()=>{
              this.getCaptchaImg()
              this.loading = false
            })
          }
        })
      }else{
        this.$refs.mobileLoginForm.validate((valid)=>{
          if(valid){
            this.loading=true;
            smsCodeLogin(this.form.mobile,this.form.smsCode).then(res=>{
              if(res.code===200){
                this.handleSuccess(res)
              }else{
                this.loading = false
              }
            }).catch(()=>{
              this.loading=false;
            }).finally(()=>{
              this.loading=false;
            })
          }
        })
      }
    },
    getCaptchaImg(){
      this.form.t = new Date().getTime()
      this.captchaImg='http://localhost:8020/code?t=' + this.form.t
    },
    handleSuccess(res){
      setToken(res.data.accessToken)
      this.$router.push({
        name: this.$config.homeName
      })
      setTimeout(() => {
        this.$Message.success(`${timeFix()}，欢迎回来`)
      }, 1000)
    },
    handleDropDown(name){
      this.$Message.error('开发中……')
      // if(name==='resetByEmail'){
      //   this.$router.push({path:'/forget'})
      // }
    },
    toGithubLogin(){

    },
    toQQLogin(){

    },
    toWeixinLogin(){

    },
    toPayLogin(){

    },
    countDown(){
      let that = this;
      if (this.count == 0) {
        this.text='获取验证码';
        this.clickFlag=false;
        this.count=60
        return ;
      } else {
        this.text = this.count + " 秒后重试";
        this.count--;
        this.clickFlag=true;
      }
      setTimeout(function() {
        that.countDown();
      }, 1000);
    },
    sendSmsCode() {
      if (isNull(this.form.mobile)) {
        this.$Message.error('手机号码不能为空');
        return;
      }
      if (!validatePhone(this.form.mobile)) {
        this.$Message.error('手机号码不正确');
        return;
      }
      sendCode(this.form.mobile).then(res => {
        if (res.code === 200) {
          this.$Message.success('发送成功.');
          this.countDown();
        }
      })
    },
    onConnected (frame) {
      let _that = this
      console.log(frame)
      _that.stompClient = Stomp.over(new SockJS("http://127.0.0.1:8080/ws"), this.responseCallback(), this.onFailed())
      console.log('连接已建立--------------')
      // 向服务器发起websocket连接
      _that.stompClient.connect({}, (frame) => {
        _that.stompClient.subscribe("/topic/subscribe", (msg) => {
          console.log('msg-----------', msg)
        })
        _that.stompClient.subscribe("/user/" + this.form.username + "/queue/subscribe", (msg) => {
          console.log('msg-----------', msg)
        })
      }, (err) => {
        console.log(err)
      })
      // 断开连接
      _that.disconnect = () => {
        if (_that.stompClient != null) {
          _that.stompClient.disconnect()
        }
      }
    },
    onFailed (frame) {
      console.log('Failed: ' + frame)
    },
    responseCallback (frame) {
      console.log('responseCallback msg=>' + frame)
    },
// 关闭连接
    closeWebSocket () {
      this.disconnect()
    }

  },
  mounted(){
    this.getCaptchaImg();
    this.onConnected();
  },
}
</script>


<style lang="less">
@import "./login.less";
.header {
  margin-top: 8vh;
  margin-bottom: 5vh;
  text-align: center;

  .description {
    font-size: 18px;
    color: rgba(0, 0, 0, 0.45);
    margin-top: 1vh;
  }
}
</style>
